/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.farmcode.web.generation.template;

import com.farmcode.api.runtime.regex.Match;
import com.farmcode.base.manager.FacadeException;
import com.farmcode.console.api.business.custom.ExtTemplateManager;
import com.farmcode.console.api.model.Project;
import com.farmcode.console.api.model.Template;
import com.farmcode.web.BaseFARMCodeBacking;
import com.farmcode.web.generation.match.MatchContextBackingBean;
import com.farmcode.web.generation.match.MatchContextPopup;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.RequestScoped;
import javax.inject.Named;

/**
 *
 * @author Oscar Ivan Prado
 */
@Named(value = "templateBackingBean")
@RequestScoped
public class TemplateBackingBean extends BaseFARMCodeBacking{
    
    public static final String TEMPLATES_SESSION_NAME= TemplateBackingBean.class + ".templates";
    public static final String TEMPLATE_ID_SESSION_NAME = TemplateBackingBean.class + ".templateId";
    public static final String TEMPLATE_SELECTED = TemplateBackingBean.class.getName() + ".templateSelected";
    
    private List<Template> templates;
    
    @EJB
    private ExtTemplateManager extTemplateManager;
    
    /** Creates a new instance of TemplateBackingBean */
    public TemplateBackingBean() {
    }
    
    public void onTemplateSelected(Template template){
//        getSession().setValue(new Match().getClass().getCanonicalName(), new Match());
        getSession().setValue(TEMPLATE_SELECTED, template);
        getSession().setValue(TEMPLATE_ID_SESSION_NAME, template.getId());
        openLookUp(MatchContextBackingBean.class);
    }

    /**
     * @return the templates
     */
    public List<Template> getTemplates() throws FacadeException {
        templates = new ArrayList<Template>();
        if (getSession().getValue(TEMPLATES_SESSION_NAME) != null) {
            templates = getSession().getValue(TEMPLATES_SESSION_NAME);
        } else {
            Project project = getProject();
            if (project != null && project.getId() != null) {
                List<Template> tmpTemplates = extTemplateManager.getTemplatesByPackage(project.getPackageTemplate());
                for (Template template : tmpTemplates) {
                    template.setSelected(true);
                }
                setTemplates(tmpTemplates);
            }
        }
        return templates;
    }
    
     /**
     * @param templates the templates to set
     */
    public void setTemplates(List<Template> templates) {
        this.templates = templates;
        getSession().setValue(TEMPLATES_SESSION_NAME, templates);
    }
    
   
}
